/**
 * http://usejsdoc.org/
 * @util upload
 */
var VIEW = __dirname + '/../../view/',
	formidable = require("formidable"),
	fs = require('fs'),
	util = require('util'),
	BASE_DIR = __dirname,
	dgram = require('dgram');
module.exports = function(){
	var _res = arguments[0];
	var _req = arguments[1];
	
	/**
	 * @desc HTTP 响应文件上传页面
	 */
	this.uploadPage = function(){
		_res.render(VIEW + 'index.jade');
	};
	
	/**
	 * @desc 文件上传处理逻辑
	 */
	this.uploadAction = function(){
		var now = Date.parse(new Date())/1000;
		var form = new formidable.IncomingForm(),
			fields = [],
			baseName = BASE_DIR + '/uploadFile' + now,
			imageName = baseName + '.png',
			newName = baseName + '_small' + '.png',
			pathName = '/uploadFile' + now + '_small' + '.png';
		
		/**根据form 表单获取其中的HTTP 参数*/
		form.on('field',function(field,value){
			fields.push([field,value]);
		});
		
		form.parse(_req,function(error,fields,files){
			var size = '' + fields.width + 'x' + fields.height;
			
//			fs.renameSync(files.image.path,imageName);
			console.log(files);
			var readStream = fs.createReadStream(files.image.path);
			var writeStream = fs.createWriteStream(imageName);
			
			/**util.pump 和readStream.pipe 用法一样，前者已过时*/
			util.pump(readStream, writeStream, function(){
				fs.unlinkSync(files.image.path);
			});
			imageResize(fields.width,fields.height,imageName,newName);
		});
	};
	
	
	/**
	 *@desc 图片压缩处理函数
	 *@parameters width 图片压缩的宽度
	 *@parameters height 图片压缩的高度
	 *@parameters imagePath 图片源地址
	 *@parameters newName 图片处理后的路劲名称
	 */
	function imageResize(width,height,imagePath,newName){
		var imageJson = {
			'width' : width,
			'height': height,
			'url':imagePath,
			'new_name':newName
		};
		
		var jsonStr = JSON.stringify(imageJson);
		var client = dgram.createSocket("upd4");
		var message = new Buffer(jsonStr);
		/**应用UDP客户端发送信息到UDP到服务端*/
		client.send(message,0,message.length,41234,"127.0.0.1",function(){
			client.on("message",function(msg,rinfo){
				var retJson = JSON.parse(msg);
				if(retJson.code === 0){ //成功处理后响应正确信息到web客户端
					console.log(pathName);
					_res.render(VIEW + 'main.jade',{'url':pathName,'err':'ok'});
				}else{
					_res.render(VIEW + 'main.jade',{'url':pathName,'err':'error'});
				}
			});
		});
		
	}
};